class MySingleLinkedList {
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//代表链表的头结点

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void display(ListNode newHead) {
        ListNode cur = newHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void addFirst(int val) {
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
    }

    public int kthToLast(int k) {
        if (k <= 0 || head == null) {
            return -1;
        }
        ListNode fast = head;
        ListNode slow = head;
        //1. 先让fast走k-1步
        int count = 0;
        while (count != k - 1) {
            fast = fast.next;
            if (fast == null) {
                return -1;
            }
            count++;
        }
        //2. 然后一起走，当fast走到最后一个结点的时候，slow的位置就是返回倒数第k个结点的位置
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;
    }
}

public class Demo2_4 {
    //返回倒数的第k个结点
    //实现一种算法，找出单向链表中倒数第 k 个节点。返回该节点的值。
    public static void main(String[] args) {
        MySingleLinkedList msl = new MySingleLinkedList();
        msl.addFirst(1);
        msl.addFirst(2);
        msl.addFirst(3);
        msl.addFirst(10);
        msl.addFirst(5);
        msl.display();
        int ret = msl.kthToLast(2);
        System.out.println(ret);
    }
}
